package com.coocaa.x.demo.servlets;

import android.os.RemoteException;

import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.liteplayer.aidl.ILitePlayerListener;
import com.coocaa.x.service.liteplayer.aidl.ReadyInfo;
import com.coocaa.x.service.liteplayer.aidl.VideoSourceInfo;
import com.coocaa.x.service.litewebserver.webserver.LiteWebHttpd;
import com.coocaa.x.service.litewebserver.webserver.NanoHTTPD;
import com.coocaa.x.service.litewebserver.webserver.servlet.Servlet;
import com.skyworth.plugin.parser.jni.videoinfo;
import com.skyworth.plugin.parser.jni.videoparse;

import java.io.InputStream;
import java.util.Map;

/**
 * Created by lu on 15-9-9.
 */
public class PlayerServlet extends Servlet {
    private ServletInfo info = null;
//    private videoparse parser = null;

    @Override
    protected void onCreate() {
        getSessionHandler().addHandler("/play", playHandler);
        getSessionHandler().addHandler("/pause", pauseHandler);
        getSessionHandler().addHandler("/seek", seekHandler);
        getSessionHandler().addHandler("/info", infoHandler);
//        parser = new videoparse();
        try {
            XServiceManager.getLitePlayerClientService().getPlayerMonitor().addPlayerListener(playerListener);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        try {
            XServiceManager.getLitePlayerClientService().getPlayerMonitor().removePlayerListener(playerListener);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
//        parser = null;
    }

    @Override
    protected NanoHTTPD.Response onServe(NanoHTTPD.IHTTPSession session) {
        return getSessionHandler().handle(session);
    }

    @Override
    protected InputStream getResource(String uri) {
        return null;
    }

    @Override
    public synchronized ServletInfo getServletInfo() {
        if (info == null) {
            info = new ServletInfo();
            info.vendorName = "superx";
            info.servletName = "player";
            info.versionCode = 1;
            info.versionName = "1.0.0";
        }
        return info;
    }

    private ILitePlayerListener.Stub playerListener = new ILitePlayerListener.Stub() {
        @Override
        public void onProgressChanged(int timeInMilliSeconds) throws RemoteException {

        }

        @Override
        public void onPlayStarted(String videoName, int durationInMilliSeconds) throws RemoteException {

        }

        @Override
        public void onPlayPaused() throws RemoteException {

        }

        @Override
        public void onPlayResumed() throws RemoteException {

        }

        @Override
        public void onPlayStopped() throws RemoteException {

        }

        @Override
        public void onPrepared() throws RemoteException {

        }

        @Override
        public void onBufferingUpdate(int percent) throws RemoteException {

        }

        @Override
        public void onCompletion() throws RemoteException {

        }

        @Override
        public boolean onInfo(int what, int extra) throws RemoteException {
            return false;
        }

        @Override
        public boolean onError(int what, int extra) throws RemoteException {
            return false;
        }
    };

    private LiteWebHttpd.ServletHandler playHandler = new LiteWebHttpd.ServletHandler() {
        private static final String P_SRC_NAME = "src_name";
        private static final String P_SRC_URL = "src_url";

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            Map<String, String> parmas = session.getParms();
            String src_name = parmas.get(P_SRC_NAME);
            String src_url = parmas.get(P_SRC_URL);
//            if (src_name != null && !src_name.equals("") && src_url != null && !src_url.equals("")) {
//                try {
//                    videoinfo info = parser.getParse(src_url);
//
//                    VideoSourceInfo vs = new VideoSourceInfo();
//                    if (info.HighUrl != null && !info.HighUrl.equals(""))
//                        vs.url = info.HighUrl;
//                    else if (info.NomalUrl != null && !info.NomalUrl.equals(""))
//                        vs.url = info.NomalUrl;
//
//                    ReadyInfo ri = new ReadyInfo();
//                    ri.name = src_name;
//
//
////                    XServiceManager.getLiteCCConnectorService().startPlayer(src_name, vs.url, false);
//
//                    XServiceManager.getLitePlayerClientService().getPlayer().getReady(ri);
//                    XServiceManager.getLitePlayerClientService().getPlayer().start(vs, src_name);
//                    r = newResponseMessage(null);
//                } catch (RemoteException e) {
//                    ResponseMessage msg = new ResponseMessage();
//                    msg.error_code = -1;
//                    msg.error_msg = e.getMessage();
//                    r = newResponseMessage(msg);
//                }
//            } else {
                ResponseMessage msg = new ResponseMessage();
                msg.error_code = -3;
                msg.error_msg = "params error src_name=" + src_name + "  src_url=" + src_url;
                r = newResponseMessage(msg);
//            }
            return r;
        }
    };

    private LiteWebHttpd.ServletHandler pauseHandler = new LiteWebHttpd.ServletHandler() {
        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            try {
                if (XServiceManager.getLitePlayerClientService().getPlayer().isPlaying())
                    XServiceManager.getLitePlayerClientService().getPlayer().pause();
                r = newResponseMessage(null);
            } catch (RemoteException e) {
                ResponseMessage msg = new ResponseMessage();
                msg.error_code = -1;
                msg.error_msg = e.getMessage();
                r = newResponseMessage(msg);
            }
            return r;
        }
    };

    private LiteWebHttpd.ServletHandler seekHandler = new LiteWebHttpd.ServletHandler() {
        private static final String P_SEEK_TO = "seek_to";

        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            Map<String, String> parmas = session.getParms();
            String seek_to = parmas.get(P_SEEK_TO);
            try {
                int _seek_to = Integer.valueOf(seek_to);
                if (XServiceManager.getLitePlayerClientService().getPlayer().isPlaying()) {
                    XServiceManager.getLitePlayerClientService().getPlayer().seekTo(_seek_to);
                }
                r = newResponseMessage(null);
            } catch (Exception e) {
                ResponseMessage msg = new ResponseMessage();
                msg.error_code = -1;
                msg.error_msg = e.getMessage();
                r = newResponseMessage(msg);
            }
            return r;
        }
    };

    private LiteWebHttpd.ServletHandler infoHandler = new LiteWebHttpd.ServletHandler() {
        class InfoResponseMessage extends ResponseMessage {
            public long length, position;
            public String state;
        }

        private static final String PLAYER_STATE_PLAYING = "playing";
        private static final String PLAYER_STATE_PAUSED = "paused";


        @Override
        public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
            NanoHTTPD.Response r;
            try {
                int length = XServiceManager.getLitePlayerClientService().getPlayer().getDuration();
                int position = XServiceManager.getLitePlayerClientService().getPlayer().getCurrentTimeInMillis();
                String state = PLAYER_STATE_PAUSED;
                if (XServiceManager.getLitePlayerClientService().getPlayer().isPlaying())
                    state = PLAYER_STATE_PLAYING;
                InfoResponseMessage msg = new InfoResponseMessage();
                msg.length = length;
                msg.position = position;
                msg.state = state;
                r = newResponseMessage(msg);
            } catch (Exception e) {
                ResponseMessage msg = new ResponseMessage();
                msg.error_code = -1;
                msg.error_msg = e.getMessage();
                r = newResponseMessage(msg);
            }
            return r;
        }
    };
}
